package com.wwwc.index.web.servlet;

import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.ServletRequestWrapper;
import java.net.*;

import com.wwwc.util.web.*;
import com.wwwc.index.web.ejb.database.*;

public class UserInputCheck {
    EJBDatabaseQuery ejbdb;
    ResourceBundle errorInfo;

    UserInputCheck (HttpServletRequest request) {
	Locale locale = request.getLocale();
	locale = locale.getDefault();
	this.errorInfo = ResourceBundle.getBundle("UserInputCheck", locale.getDefault()); 
    }

    public String required (String name, String input) {
	if(name == null) {
	    return("UserInputCheck.size:Error:(no name).");
	}

	if(input==null || input.length()==0) {
	    return("["+name+"] "+errorInfo.getString("required")+".");
	}
	return null;
    }

    public String checkSize(String name, String input, int mini, int max, String type) {
	if(name == null || input == null) {
	    return("UserInputCheck.size:Error:(no name or input).");
	}

	if(input.length() < mini) {
	    return("["+name+"] "+errorInfo.getString("tooShort") +". ("+mini+"-"+max+" "+type+").");
	}

	if(input.length() > max) {
	    return("["+name+"] "+errorInfo.getString("tooLong") +". ("+mini+"-"+max+" "+type+").");
	}
	return null;
    }

    public String userNameInUse (String field_name, String input) {
	try {
	    if (ejbdb == null) {
		ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	    }
	    
	    if(ejbdb.userNameInUse(input)) {
		return (""+field_name+"["+input+"] "+errorInfo.getString("unavaiable")+
			". "+errorInfo.getString("ifYouAre")+" owner of ["+input+"], "+
			errorInfo.getString("pleaseSignIn")+"!");
	    }
	}
	catch (Exception e) {
	    System.out.println("UserInputCheck:userNameInUse:Error:"+e);
	    return (errorInfo.getString("tryAgain")+"!");
	}
	return null;
    }

    public String checkFormat (String field_name, String input, String format) {
	for (int i=0; i< input.length(); i++) {
	    String temp = input.charAt(i)+"";
	    if(format.indexOf(temp) == -1) {
		if(temp.equals(" ")) {
		    temp="SPACE";
		}
		return ("["+temp+"] "+errorInfo.getString("formatError")+" ["+field_name+"]!");
	    }
	}
	return null;
    }

    public String checkUrl (String field_name, String url) {
	if(!MyUserInputCheck.isUrl(url)) {
	    return (errorInfo.getString("Field")+" ["+field_name+"] "+
		    errorInfo.getString("ConnectTo")+" ["+url+"] "+errorInfo.getString("error")+".");
	}
	return null;
    }
}






